﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Data;

namespace AuthenticationWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<IdentityUser> _userManager;

        public LoginController(ILogger<LoginController> logger,RoleManager<IdentityRole> roleManager,UserManager<IdentityUser> userManager)
        {
            _logger = logger;
            _roleManager = roleManager;
            _userManager = userManager;
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CreateUser()
        {
            bool roleExists = await _roleManager.RoleExistsAsync("admin");
            if (!roleExists)
            {
                IdentityRole role = new IdentityRole { Name = "admin" };
                var r = await _roleManager.CreateAsync(role);
                if (!r.Succeeded)
                {
                    return BadRequest(r.Errors);
                }
            }
            IdentityUser? user = await _userManager.FindByNameAsync("wja");
            if (user == null)
            {
                user = new IdentityUser { UserName = "wja", Email = "1258399119@qq.com", EmailConfirmed = true };
                var r = await _userManager.CreateAsync(user, "123456");
                if (!r.Succeeded)
                {
                    return BadRequest(r.Errors);
                }
                r = await _userManager.AddToRoleAsync(user, "admin");
                if (!r.Succeeded)
                {
                    return BadRequest(r.Errors);
                }
            }
            return Ok();
        }

        //写一个登录的接口
        /// <summary>
        /// 登录
        /// </summary>
        

    }
}
